<?php
header("Access-Control-Allow-Origin: *");

// 允许特定方法
header("Access-Control-Allow-Methods: z`POST, GET, OPTIONS");

// 允许前端发送的请求头，如 content-type
header("Access-Control-Allow-Headers: Content-Type");
include_once './utils/conn.php';

//登陆
if (isset($_POST["action"]) && $_POST["action"] == "login") {
    $user = [
        "username" => $_POST["username"],
        "password" => $_POST["password"]
    ];
    login($conn, $user);
}

//登陆
if (isset($_POST["action"]) && $_POST["action"] == "register") {
    $user = [
        "username" => $_POST["username"],
        "password" => $_POST["password"]
    ];
    register($conn, $user);
}
function login($conn, $user)
{
    //使用php把明文加密为密文
    $password = hash("sha256", $user["password"]);
    $sql = "select count(*) as count from login where username='" . $user["username"] . "' and password='" . $password . "'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $count = $row["count"];
    if ($count > 0) {
        //登陆成功
        echo json_encode(["code" => 1, "msg" => "登陆成功", "data" => null], JSON_UNESCAPED_UNICODE);
    } else {
        //登陆失败
        echo json_encode(["code" => 0, "msg" => "登陆失败", "data" => null], JSON_UNESCAPED_UNICODE);
    }
}

function register($conn, $user)
{

    $password = hash('sha256', $user["password"]);
    $sql = "insert into login values('" . $user['username'] . "','" . $password . "')";
    $result = mysqli_query($conn, $sql);
    if ($result) {
        echo json_encode(["code" => 1, "msg" => "注册成功", "data" => null], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode(["code" => 1, "msg" => "注册成功", "data" => null], JSON_UNESCAPED_UNICODE);
    }
}
